<template>
    <AnalysisAnimation v-if="showAnalysisAnimation" :duration="duration" @complete="AnalysisAnimationComplete" />

    <div v-if="currentPage === 'intro'"
        class="max-w-3xl mx-auto bg-slate-900/80 rounded-xl shadow-lg overflow-hidden p-8 backdrop-blur-sm border border-indigo-500/30 tech-card animate-fade-in">
        <h2 class="text-2xl font-bold text-indigo-200 mb-6 glow-text">九型人格测试说明</h2>
        <div class="space-y-4 text-slate-300">
            <p>九型人格是一种性格分类系统，它将人的性格分为九种基本类型。通过144道精心设计的选择题，本测试将帮助您深入了解自己的核心人格特质。</p>
            <p class="font-medium">测试须知：</p>
            <ul class="list-disc pl-6 space-y-2">
                <li>本测试包含144道二选一题目</li>
                <li>预计完成时间约45分钟</li>
                <li>请根据第一直觉选择最符合您的选项</li>
                <li>测试过程中可以返回修改之前的答案</li>
                <li>完成测试后，您将获得详细的性格分析报告</li>
            </ul>
        </div>
        <div class="mt-8 text-center">
            <button @click="startTest"
                class="tech-button whitespace-nowrap bg-gradient-to-r from-indigo-600 to-indigo-500 hover:from-indigo-500 hover:to-indigo-400 text-white font-medium py-3 px-8 text-lg relative overflow-hidden">
                <span class="relative z-10">开始测试</span>
                <span class="button-glow"></span>
            </button>
        </div>
    </div>

    <!-- Test Page -->
    <div v-if="currentPage === 'test'"
        class="max-w-4xl mx-auto bg-slate-900/80 rounded-xl shadow-lg overflow-hidden backdrop-blur-sm border border-indigo-500/30 tech-card animate-slide-up">
        <div class="tech-decorations">
            <div class="tech-corner top-left"></div>
            <div class="tech-corner top-right"></div>
            <div class="tech-corner bottom-left"></div>
            <div class="tech-corner bottom-right"></div>
        </div>
        <!-- Progress Bar -->
        <div class="bg-slate-800/90 px-6 py-4 border-b border-indigo-500/20">
            <div class="flex justify-between items-center mb-2">
                <span class="text-sm font-medium text-indigo-200">进度: {{ currentQuestionIndex }}/{{ questionTotal
                    }}</span>
                <span class="text-sm font-medium text-indigo-200">剩余时间: {{ formatTime(remainingTime) }}</span>
            </div>
            <div class="w-full bg-slate-700 rounded-full h-2.5 overflow-hidden">
                <div class="progress-bar h-2.5 rounded-full"
                    :style="{ width: `${(currentQuestionIndex / questionTotal) * 100}%` }"></div>
            </div>
        </div>

        <!-- Question Area -->
        <div class="p-8">
            <h2 class="text-xl font-semibold text-indigo-200 mb-8">{{ `问题 ${currentQuestionIndex + 1}: ` +
                currentQuestion.title }}</h2>

            <div class="space-y-4">
                <div v-for="(option, index) in 2" :key="index" @click="selectOption(index)"
                    class="p-4 border-2 rounded-lg cursor-pointer transition-all duration-300 option-card" :class="{
                        'border-indigo-500 bg-indigo-900/50 transform scale-[1.02] shadow-glow': selectedOption === index,
                        'border-slate-700 hover:border-indigo-400 bg-slate-800/50': selectedOption !== index,
                        'opacity-50 !cursor-not-allowed': isSubmitting, // 新增禁用样式
                    }">
                    <div class="flex items-cente r">
                        <div class="w-6 h-6 rounded-full border flex items-center justify-center mr-3 transition-all duration-300"
                            :class="{
                                'border-indigo-500 shadow-glow-sm': selectedOption === index,
                                'border-slate-600': selectedOption !== index,
                            }">
                            <div v-if="selectedOption === index"
                                class="w-3 h-3 rounded-full bg-indigo-500 animate-pulse"></div>
                        </div>
                        <span class="text-slate-300">{{
                            option == 1 ? '选项 A: ' + currentQuestion.option_a_text : '选项 B: ' +
                                currentQuestion.option_b_text
                            }}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Navigation -->
        <div class="bg-slate-800/90 px-8 py-6 flex justify-between border-t border-indigo-500/20">
            <button @click="prevQuestion" :disabled="currentQuestionIndex === 0"
                class="tech-button-secondary whitespace-nowrap px-6 py-2 border border-indigo-500/50 text-indigo-200 disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-300">
                上一题
            </button>
            <button @click="nextQuestion" :disabled="selectedOption === null"
                class="tech-button whitespace-nowrap px-6 py-2 bg-gradient-to-r from-indigo-600 to-indigo-500 text-white disabled:opacity-30 disabled:cursor-not-allowed relative overflow-hidden">
                <span class="relative z-10">{{ currentQuestionIndex >= questionTotal - 1 ? '查看结果' : '下一题' }}</span>
                <span class="button-glow"></span>
            </button>
        </div>
    </div>

    <!-- Analysis Animation -->
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserInfo } from '/@/stores/userInfo'
import { ElMessage } from 'element-plus'
import { index, start, submit, calculate } from '/@/api/frontend/enneagram/index'
import AnalysisAnimation from '/@/components/AnalysisAnimation.vue'
import { getSeoConfig } from '/@/api/frontend/index'
import { useSeo } from '/@/stores/seo'
import { da } from 'element-plus/es/locale/index.mjs'

const questionTotal = ref(144)
const router = useRouter()
const userInfo = useUserInfo()

// Test data
interface Question {
    title: string
    option_a_text: string
    option_b_text: string
    [key: string]: any
}

const questions = ref<Question[]>([])
let id = 0 //result_id
const randomNumber = 500 + Math.floor(Math.random() * 1500)
const duration = ref(randomNumber)
const AnalysisAnimationComplete = () => {
    showAnalysisAnimation.value = false
}

const showAnalysisAnimation = ref(false)

// State
const currentPage = ref<'intro' | 'test'>('intro')
const currentQuestionIndex = ref(0)
const selectedOption = ref<number | null>(null)
const remainingTime = ref(45 * 60) // 45 minutes in seconds
const timer = ref<NodeJS.Timeout | null>(null)

interface Answers {
    [key: number]: 'a' | 'b' | undefined
}
const answers = reactive<Answers>({})
const currentQuestion = computed(() => {
    return questions.value[currentQuestionIndex.value] || { title: '', option_a_text: '', option_b_text: '' }
})

// 检查登录状态
const checkLoginStatus = () => {
    if (!userInfo.isLogin()) {
        router.push('/login')
        return false
    }
    return true
}

// Methods
const startTest = () => {
    // 检查登录状态
    if (!checkLoginStatus()) {
        return
    }

    start().then((res) => {
        id = res.data.id
        currentPage.value = 'test'
        startTimer()
    }).catch((error) => {
        console.error('开始测试失败:', error)
        ElMessage.error('开始测试失败，请重试')
    })
}

const isSubmitting = ref(false) // 新增提交状态

const selectOption = (index: number) => {
    if (isSubmitting.value) return // 如果正在提交，直接返回

    const question_id = getAnswerKey(currentQuestionIndex.value)
    answers[question_id] = index === 0 ? 'a' : 'b'
    selectedOption.value = index
    isSubmitting.value = true // 开始提交

    submit({ id, question_id, selected_option: answers[question_id] })
        .then((res) => {
            nextQuestion()
        })
        .finally(() => {
            isSubmitting.value = false // 提交完成
        })
}
const startTimer = () => {
    if (timer.value) clearInterval(timer.value)
    timer.value = setInterval(() => {
        remainingTime.value--
        if (remainingTime.value <= 0) {
            finishTest()
        }
    }, 1000)
}

const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`
}

const getAnswerKey = (currentQuestionIndex: number) => {
    return currentQuestionIndex + 1
}

const prevQuestion = () => {
    if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
        const answerKey = getAnswerKey(currentQuestionIndex.value)
        selectedOption.value = answers[answerKey] === 'a' ? 0 : answers[answerKey] === 'b' ? 1 : null
    }
}

const nextQuestion = () => {
    if (selectedOption.value !== null) {
        if (currentQuestionIndex.value < questionTotal.value - 1) {
            currentQuestionIndex.value++
            const answerKey = getAnswerKey(currentQuestionIndex.value)
            selectedOption.value = answers[answerKey] === 'a' ? 0 : answers[answerKey] === 'b' ? 1 : null
        } else {
            currentQuestionIndex.value++
            finishTest()
        }
    }
}
//自动提交计算
const autoCalc = (bc?: (arg: any) => void) => {
    return calculate({ id }).then((res) => bc && bc(res))
}
const finishTest = () => {
    if (timer.value) clearInterval(timer.value)
    showAnalysisAnimation.value = true
    autoCalc(() => {
        setTimeout(() => {
            duration.value = 0
            showAnalysisAnimation.value = false
            router.push({ name: 'poster', params: { id } })
        }, 1000)
    })
}

onMounted(() => {
    // 首次进入首页时获取并持久化 SEO（若未初始化）
    const seo = useSeo()
    console.log('seo init')
    getSeoConfig().then((data) => {
        console.log(data)
        seo.setSeo(data)
    })

    index()
        .then((res) => {
            questions.value = res.data.questions
            questionTotal.value = res.data.total_questions || res.data.questions?.length || 0
            remainingTime.value = res.data.time_limit_minutes ? res.data.time_limit_minutes * 60 : 45 * 60
        })
        .catch((err) => {
            console.log(err)
        })
    return () => {
        if (timer.value) clearInterval(timer.value)
    }
})
</script>

<style scoped lang="scss"></style>
